package com.zheng.study.web.shiro.service;

import com.zheng.study.base.service.redis.RedisService;
import com.zheng.study.company.entity.Admin;
import com.zheng.study.company.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Service - shiro 相关
 * ============================================================================
 * author : fallenpanda
 * createDate:  2018/8/17 。
 * ============================================================================
 */
@Service
public class ShiroService {

	private static final String appId1 = "b35d7751bc8ef46b87892a6abcb8f8";
	private static final String appSecret1 = "b35d7751bc8ef46b87892a6abcb8f86ede884481ef2e94aa49a7b48fffd4c13c";

	private static final String appId2 = "f86ede884481ef2e94aa49a7b48";
	private static final String appSecret2 = "b35d7751bc8ef46b87892a6abcb8f86ede884481ef2e94aa49a7b48fffd4c13c";

	private static final String APP_ID_UUID_REQUEST_TIMESTAMP = "app:$1:$2:request_timestamp";
	private static final String USER_UID_SECRET_INFO = "user:%s:secret";

	private static final int TTLDAY = 24*60*60;
	private static final int TTLQUART = 15*60;

	@Autowired
	private RedisService redisService;
	@Autowired
	private AdminService adminService;

	public String getUserSecretByAdminId(String adminId) {
		Admin admin = adminService.get(adminId);
		if (admin != null) {
			return admin.getSecret();
		}
		return null;
	}

	public String getAppSecretByAppId(String appId) {
		if(appId1.equals(appId)){
			return appSecret1;
		}else if(appId2.equals(appId)){
			return appSecret2;
		}
		return null;
	}

	/**
	 * 同一个终端的时间戳每次访问时间不能小于上次时间
	 *
	 * @param appId
	 * @param uuid
	 * @param timestamp
	 * @return
	 */
	public boolean compareAndSetAppTimestamp(String appId, String uuid, String timestamp){
		String key = StringUtils.replace(APP_ID_UUID_REQUEST_TIMESTAMP,"$1",appId);
		key = StringUtils.replace(key,"$2",uuid);
		if(redisService.exists(key)){
			String lastTimestamp = redisService.get(key);
			if(StringUtils.isNotEmpty(lastTimestamp)){
				long l = Long.parseLong(lastTimestamp);
				long t = Long.parseLong(timestamp);
				if(t <= l){
					return false;
				}
			}
		}
		redisService.set(key, timestamp);
		redisService.expire(key,TTLQUART);
		return true;
	}

}
